module Admin
	class ImportResourcesController < ApplicationController
		def import_stocks

		  stocks = Stock.find_all_from_sina		
		
		  stocks.andand.each do |stock|
				Stock.create stock unless Stock.exists?(:stock_no=>stock[:stock_no])
		  end
		  
		  redirect_to(admin_stocks_path)
		end
		
		def import_balance_sheets
		  import_resources(BalanceSheet)
		end
		
		def import_cash_flow_statements
		  import_resources(CashFlowStatement)
		end
		
		def import_profit_statements
			import_resources(ProfitStatement)
		end
		
		private 
		def import_resources(resourceClass)
			Stock.find(:all).andand.each do |stock|
				time = 0
				if resourceClass.exists?(:stock_no=>stock.stock_no)
					next unless params[:force] == 'true'
				end
						
			
				begin
				  records = resourceClass.find_by_stock_no_from_sina(stock.stock_no)
				  
				  resourceClass.transaction do
						records.andand.each do |key, value|        
						  report = value.merge :stock_no=>stock.stock_no, :report_date=>key

							if !resourceClass.exists?(:report_date=>report[:report_date], :stock_no=>stock.stock_no)
							  resourceClass.create report
							end
						end      
				  end
				rescue EOFError => err
					time += 1				
					retry if time < 10
					raise err
				end
		  end
		  
		  redirect_to(admin_stocks_path)
		end
	end
end

